import store from '../store';
import axios from '../plugins/http';
import api from "../api/commonApi";

export function getBaseDictName(dicName, val) {
  if (!dicName) return '';
  const storeData = store.state.baseDict[dicName];
  if (!storeData) {
    // 如果字典数据不存在，则触发异步加载
    loadDictionary(dicName);
  }
  const item = storeData ? storeData.find((item) => item.value === val) : null;
  return item ? item.code : val;
}

// 使用 Set 来跟踪正在进行的字典加载操作
const loadingDictionaries = new Set();

async function loadDictionary(dicName) {
  if (loadingDictionaries.has(dicName)) {
    // 如果字典已经在加载中，则直接返回
    return;
  }
  loadingDictionaries.add(dicName); // 标记字典正在加载

  try {
    const response = await axios.post(api.findParentType, {
      parentType: dicName
    });
    if (response.data.code === 1) {
      const ret = response.data.object;
      store.state.baseDict[dicName] = ret;
    }
  } catch (error) {
    console.error('Error fetching dictionary data:', error);
  } finally {
    loadingDictionaries.delete(dicName); // 无论成功或失败，都从加载集中移除
  }
}